<?php

namespace Api\Model;

use Think\Model;

class CouponModel extends Model {

    /**
     *  检查coupon是否可用
     * @param type $coupon_id
     * @param type $user_id
     */
    function checkCoupon($coupon_id, $user_id) {

        if (!is_numeric($user_id)) {
            $this->last_msg('用户不存在或已禁用');
            return false;
        }

        $coupon_info = $this->getCouponInfo($coupon_id);

        if (emptys($coupon_info)) {
            $this->last_msg('优惠卷不存在');
            return false;
        }

        if ($coupon_info['status'] != 1 || ($coupon_info['timing'] == 0 && $coupon_info['show_type'] != 1)) {
            $this->last_msg('优惠卷已经下架');
            return false;
        }
        $time = time();
        //未到自动上架的时间
        if ($coupon_info['timing'] > 0 && $coupon_info['timing'] > $time) {
            $this->last_msg('优惠卷已下架');
            return false;
        }

        if ($coupon_info['coupon_count'] <= 0 || $coupon_info['for_count'] <= 0) {
            $this->last_msg('优惠卷已被领完');
            return false;
        }

        //每个用户可领取张数
        $user_release_number = (int) $coupon_info['user_release_number'];
        $user_release_number = $user_release_number > 0 ? $user_release_number : 1;


        if ($this->getUserNumByCoupon($user_id, $coupon_id) >= $user_release_number) {
            $this->last_msg("该优惠卷每人只可以领取{$user_release_number}张");
            return false;
        }
        $AvailableInfo = $this->getCouponAvailableNum($coupon_info);

        if (is_array($AvailableInfo) && $AvailableInfo['count'] >= $coupon_info['release_number']) {
            $this->last_msg("该优惠卷设置了周期限额{$coupon_info['release_number']}张,下次可领取时间为:" . date('Y-m-d', $AvailableInfo['next_time']));
            return false;
        }
        //积分验证
        if ($coupon_info['credit'] > 0) {
            $UserCredit = D('User')->getUserCredit($user_id);
            if ($UserCredit < $coupon_info['credit']) {
                $this->last_msg("该优惠卷需要{$coupon_info['credit']}积分才可领取,您目前积分为$UserCredit");
                return false;
            }
        }
        return true;
    }

    /**
     *  领取优惠卷
     * @param type $coupon_id
     * @param type $user_id
     * @return boolean
     */
    function receiveCoupon($coupon_id, $user_id) {
        if (!$this->checkCoupon($coupon_id, $user_id))
            return false;
        $coupon_code = $this->getCoupon($coupon_id, $user_id);
        if (!$coupon_code) {
            $this->last_msg('生成优惠卷失败，请重试');
            return false;
        }
        return $coupon_code;
    }

    function getCoupon($coupon_id, $user_id, $length = 16) {
        $coupon_info = $this->getCouponInfo($coupon_id, 'shops_id,credit,discount');

        $coupon_array = array();
        $coupon_array[] = $coupon_info['shops_id'];
        $coupon_array[] = $user_id;
        $coupon_array[] = uniqid('', true);
        $coupon_array[] = mt_rand(100, 999);
        $md5 = md5(implode('', $coupon_array), false);
        $counpon_code = substr($md5, 0, $length);
        $counpon = '';
        for ($i = 0; $i < strlen($counpon_code); $i++) {

            if ($i > 1 && $i % 4 == 0)
                $counpon.='-';
            $counpon.=$counpon_code[$i];
        }
        $model = M('CouponList');
        $this->startTrans();

        $data = array(
            'shops_id' => $coupon_info['shops_id'],
            'coupon_code' => $counpon,
            'create_time' => time(),
            'status' => 1,
            'coupon_id' => $coupon_id,
            'user_id' => $user_id,
        );
        $result = $model->add($data);

        if (!$result)
            return false;
        $result = $this->where(array('id' => $coupon_id, 'for_count' => array('gt', 0)))->setDec('for_count'); //优惠卷剩余数-1
        if (!$result) {
            $this->rollback();
            return false;
        }
        //        $result = M('Shops')->where(array('id' => $coupon_info['shops_id'], 'for_count' => array('gt', 0)))->setDec('for_count'); //店铺优惠卷剩余数-1
        //        if (!$result) {
        //            $this->rollback();
        //            return false;
        //        }
        if ($coupon_info['credit'] > 0) {
            $result = M('User')->where(array('id' => $user_id, 'credit' => array('gt', 0)))->setDec('credit', $coupon_info['credit']); //扣除用户积分
            if (!$result) {
                $this->rollback();
                return false;
            }
            $credit = "-{$coupon_info['credit']}";
            //添加积分日志
            $shop_name = D('Shops')->getShopName($coupon_info['shops_id']);
            D('CreditLog')->addLog($user_id, "您领取了{$shop_name}的一张{$coupon_info['discount']}折优惠卷，扣除了{$credit}积分", $counpon, 1, $credit);
        }
        $this->commit();
        return $counpon;
    }

    /**
     * 获取优惠卷在每日、每月、每周限额内已经领取多少张
     * @param type $coupon_info
     * @return true | array(领取数量,周期开始时间,周期结束时间,下一次周期开始时间)
     */
    function getCouponAvailableNum($coupon_info) {

        //不限制领取
        if ($coupon_info['release_number'] <= 0)
            return true;
        $where = array();
        switch ($coupon_info['release_cycle']) {
            case '2':
                $monsun = getmonsun();
                $time1 = $monsun['mon'];
                $time2 = $monsun['sun'];
                break;
            case '3':
                $time1 = strtotime(date('Y-m-1'));
                $time2 = strtotime(date(('Y-m-t'))) + 86399;
                break;
            default:
                $today = strtotime(date('Y-m-d 00:00:00'));
                $time1 = $today;
                $time2 = $today + 86399;
                break;
        }
        $where['create_time'] = array(array('EGT', $time1), array('ELT', $time2));
        $model = M('CouponList');
        $count = $model->where($where)->count();
        return array('count' => $count, 'start_time' => $time1, 'end_time' => $time2, 'next_time' => $time2 + 1);
    }

    function getCouponInfo($coupon_id, $field = '*') {
        return $this->field($field)->find($coupon_id);
    }

    function getUserNumByCoupon($user_id, $coupon_id) {

        $where = array(
            'coupon_id' => $coupon_id,
            'user_id' => $user_id,
        );

        return M('CouponList')->where($where)->count();
    }

    /**
     * @name 领取用户优惠券
     * @param $user_id
     * @param $coupon_code
     * @return bool
     */
    public function receiveFromUser($user_id, $coupon_code) {
        $couponInfo = M('CouponList')->where(" `coupon_code`='{$coupon_code}' ")->order('create_time desc')->find();
        if ($couponInfo == false) {
            $this->last_msg('优惠券不存在！');
            return false;
        }
        if ($couponInfo['user_id'] == $user_id) {
            $this->last_msg('不能领取自己的优惠券！');
            return false;
        }
        if ($couponInfo['status'] != C('COUPON_STATUS.PUBLISH')) {
            $this->last_msg('该优惠券未发布！');
            return false;
        }
        if (!$this->checkCoupon($couponInfo['coupon_id'], $user_id))
            return false;
        //领取优惠券
        D('CouponList')->addPath($user_id, $coupon_code, C('COUPON_STATUS.RECEIVE'), null, $couponInfo);
        //保存优惠券路径
        M('CouponList')->where("`id`={$couponInfo['id']} ")->save(array('status' => C('COUPON_STATUS.HAS_BEEN_RECEIVED')));
        //更新用户积分
        $discount = M('Coupon')->where("`id`={$couponInfo['coupon_id']}")->getField('discount');
        $credit_value = getReceiveCredit($discount);
        D('User')->saveUserCredit($couponInfo['user_id'], $credit_value);
        //记录积分日志
        D('CreditLog')->addLog($couponInfo['user_id'], C('CREDIT_NAME.COUPON_WAS_RECEIVED') . $credit_value . '积分。', $coupon_code, C('COUPON_STATUS.HAS_BEEN_RECEIVED'), $credit_value);
        return true;
    }

}
